package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.commons.exception.TanHuaException;
import com.tanhua.dubbo.api.db.QuestionApi;
import com.tanhua.dubbo.api.db.UserApi;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.model.db.Question;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.RecommendUserVo;
import com.tanhua.model.vo.TodayBestVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.commons.lang3.RandomUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TanHuaService {

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private QuestionApi questionApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Value("${tanhua.default.recommend.users}")
    private String recommendUsers;

    /**
     * 今日佳人
     * @return
     */
    public TodayBestVo todayBest() {
        // 获取用户id
        Long userId = UserHolder.getUserId();

        // 通过用户id查询今日佳人 userId
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(userId);

        // 如果没有佳人，则给个客服
        if(recommendUser == null){
            recommendUser = new RecommendUser();
            long serviceUserId = userId%99+1;

            recommendUser.setUserId(serviceUserId);
            recommendUser.setScore(88d);

        }

        // 查询佳人信息
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());

        // 创建vo，设置属性
        TodayBestVo todayBestVo = TodayBestVo.init(userInfo, recommendUser);

        // 返回
        return todayBestVo;
    }

    /**
     * 推荐朋友
     * @param recommendUserVo
     * @return
     */
    public PageResult<TodayBestVo> recommendation(RecommendUserVo recommendUserVo) {
        //1. 分页查询推荐好友
        Long userId = UserHolder.getUserId();
        Long page = recommendUserVo.getPage();
        Long pagesize = recommendUserVo.getPagesize();
        Integer age = recommendUserVo.getAge();
        String gender = recommendUserVo.getGender();

        //1 调用服务提供者 分页查询推荐用户列表数据
        PageResult pageResult = recommendUserApi.findPage(userId,page,pagesize);



        //2 没有查询到推荐用户列表数据，则设置默认推荐好友数据
        if(recommendUserVo.getPage()==1 && CollectionUtils.isEmpty(pageResult.getItems())) {
            pageResult.setItems(getDefaultRecommendUserList());
            pageResult.setCounts(10l);
            pageResult.setPage(1l);
            pageResult.setPages(1l);
        }

        //3 获取推荐用户的ids 以及  gender age 查询userInfo
        List<RecommendUser> recommendUserList = pageResult.getItems();
        List<Long> listUserIds = new ArrayList<>();
        for (RecommendUser recommendUser : recommendUserList) {
            listUserIds.add(recommendUser.getToUserId());
        }

        UserInfo userInfoCondition = new UserInfo();
        userInfoCondition.setAge(age);
        userInfoCondition.setGender(gender);

        Map<Long,UserInfo> userInfoMap = userInfoApi.findByIds(listUserIds,userInfoCondition);

        //4 循环遍历推荐用户列表 构造 TodayBestVo 返回
        List<TodayBestVo> todayBestVoList = new ArrayList<>();
        for (RecommendUser recommendUser : recommendUserList) {
            Long recommendUserUserId = recommendUser.getToUserId();   //推荐用户的id
            UserInfo userInfo = userInfoMap.get(recommendUserUserId);
            if(userInfo != null){
                todayBestVoList.add(TodayBestVo.init(userInfo,recommendUser));
            }
        }

        return new PageResult<>(pageResult.getCounts(),pageResult.getPagesize(),pageResult.getPages()
        ,pageResult.getPage(),todayBestVoList);
    }


    /**
     * 默认客服
     * @return
     */
    private List<RecommendUser> getDefaultRecommendUserList(){
        List<RecommendUser> list = new ArrayList<>();
        // 随机产生开始的客户id, 从这个客服的id开始，往后取10个
        int startIndex = RandomUtils.nextInt(1,90);
        RecommendUser recommendUser = null;
        for (long i = startIndex; i<startIndex+10; i++) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(i);
            recommendUser.setScore(RandomUtils.nextDouble(70,88));
            list.add(recommendUser);
        }
        return list;
    }

    /**
     * 佳人信息
     * @param userId
     * @return
     */
    public TodayBestVo getPersonalInfo(Long userId) {
        // 根据推荐id查询用户信息
        UserInfo userInfo = userInfoApi.findById(userId);
        // 根据当前登录的id 和 推荐的id 查询用户推荐表
        RecommendUser recommendUser = recommendUserApi.findByUserId(userId,UserHolder.getUserId());

        if(recommendUser == null){
            recommendUser.setUserId(userId);
            recommendUser.setScore(Double.valueOf(65+userId%10));
        }

        // 构造vo返回
        TodayBestVo todayBestVo = TodayBestVo.init(userInfo, recommendUser);
        return todayBestVo;
    }

    /**
     * 查询陌生人问题
     * @param userId
     * @return
     */
    public String strangerQuestions(Long userId) {
        // 根据用户id查询问题表中是否有问题
        Question question = questionApi.findUserById(userId);

        // 没有值，则设置默认值
        if(question == null || StringUtils.isEmpty(question.getTxt())){
           return "星辰大海，我们终将相遇！";
        }

        return question.getTxt();
    }

    /**
     * 回复陌生人问题
     * @param param
     */
    public void replyStrangerQuestions(Map<String,String> param) {
        /**
         * {"userId":1,"huanXinId":"hx1","nickname":"1号技师","strangerQuestion":"10012问题你服务好吗？",
         * "reply":"很好包你满意"}
         */
        Long userId = Long.valueOf(param.get("userId"));
        // 佳人的信息
        User user = userApi.findById(userId);
        Long loginUserId = UserHolder.getUserId();

        // 根据当前用户id查询用户信息详情
        UserInfo userInfo = userInfoApi.findById(loginUserId);
        User currentUser = userApi.findById(loginUserId);
        String hxUser = currentUser.getHxUser();
        String nickname = userInfo.getNickname();
        String content = strangerQuestions(userId);
        String reply = param.get("reply");

        //构造返回消息
        Map<String,Object> map = new HashMap<>();
        map.put("userId",loginUserId);
        map.put("hxUser",hxUser);
        map.put("nickname",nickname);
        map.put("strangerQuestion",content);
        map.put("reply",reply);

        if(!huanXinTemplate.sendMsg(user.getHxUser(), JSON.toJSONString(map))){
            throw  new TanHuaException(ErrorResult.error());
        }
    }

    /**
     * 探花推荐列表查询
     * @return
     */
    public List<TodayBestVo> cards() {
        Long userId = UserHolder.getUserId();   // 当前用户id
        // 调用服务随机获取 10个推荐用户数据
        List<RecommendUser> recommendUserList = recommendUserApi.findCards(userId,10);

        // 如果没有获取到推荐用户数据，则设置默认数据
        if(CollectionUtils.isEmpty(recommendUserList)){
            String[] recommendUserIds = recommendUsers.split(",");
            RecommendUser recommendUser = new RecommendUser();
            for (String recommendUserId : recommendUserIds) {
                recommendUser.setUserId(Long.valueOf(recommendUserId));
                recommendUser.setToUserId(userId);
                recommendUser.setScore(88d);
                recommendUserList.add(recommendUser);
            }
        }

        // 获取出所有的推荐用户ids userIds
        List<Long> ListUserIds = recommendUserList.stream().map(RecommendUser::getUserId).collect(Collectors.toList());

        // 根据userIds批量查询用户详情  tb_user_info
        Map<Long, UserInfo> userInfoMap = userInfoApi.findByIds(ListUserIds, null);

        // 循环遍历推荐用户数据 基于推荐用户数据以及用户详情 构造vo返回
        List<TodayBestVo> todayBestVos = new ArrayList<>();
        for (RecommendUser recommendUser : recommendUserList) {
            UserInfo userInfo = userInfoMap.get(recommendUser.getUserId());
            if(userInfo != null){
                TodayBestVo todayBestVo = TodayBestVo.init(userInfo, recommendUser);
                todayBestVos.add(todayBestVo);
            }
        }

        return todayBestVos;
    }
}
